package com.luoye_lj.dogcontroller;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;


import com.luoye_lj.dogcontroller.log.ArLog;
import com.luoye_lj.dogcontroller.log.CrashHandler;
//import com.luoye_lj.dogcontroller.util.FastBleUtils;
//import com.tencent.mmkv.MMKV;

import java.util.LinkedList;


public class CarsonBaseApplication extends Application {
    private static final String TAG = CarsonBaseApplication.class.getSimpleName();

    // 此处采用 LinkedList作为容器，增删速度快
    public static LinkedList<Activity> activityLinkedList;

    @Override
    public void onCreate() {
        super.onCreate();
//        MMKV.initialize(getApplicationContext());
//        FastBleUtils.getInstant().init(this);

        // 注册奔溃收集器
        CrashHandler crashHandler = CrashHandler.getInstance();
        crashHandler.init(this);

        //ActivityLifecycle
        activityLinkedList = new LinkedList<>();
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                ArLog.d(TAG, "onActivityCreated: " + activity.getLocalClassName());
                activityLinkedList.add(activity);
                // 在Activity启动时（onCreate()） 写入Activity实例到容器内
            }

            @Override
            public void onActivityDestroyed(Activity activity) {
                ArLog.d(TAG, "onActivityDestroyed: " + activity.getLocalClassName());
                activityLinkedList.remove(activity);
                // 在Activity结束时（Destroyed（）） 写出Activity实例
            }

            @Override
            public void onActivityStarted(Activity activity) {
            }

            @Override
            public void onActivityResumed(Activity activity) {
            }

            @Override
            public void onActivityPaused(Activity activity) {
            }

            @Override
            public void onActivityStopped(Activity activity) {
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

            }

        });
    }

    public void exitApp() {
        ArLog.d(TAG, "容器内的Activity列表如下 ");
        // 先打印当前容器内的Activity列表
        for (Activity activity : activityLinkedList) {
            ArLog.d(TAG, activity.getLocalClassName());
        }
        ArLog.d(TAG, "正逐步退出容器内所有Activity");
        // 逐个退出Activity
        int size=activityLinkedList.size();
        for (int i=size-1;i>=0;i--) {
            Activity activity= activityLinkedList.get(i);
            activity.finish();
        }
        // 结束进程
        // System.exit(0);
    }
}